package com.alpsot.spotcheck.activity;

import java.io.IOException;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import cn.pda.hf.Ax6737Reader;
import cn.pda.hf.H910Reader;
import cn.pda.scan.CardThread;
import cn.pda.utils.HfDevice;

import com.alpsoft.spotcheck.impl.HandleMsg;
import com.alpsoft.spotcheck.model.User;
import com.alpsoft.spotcheck.util.DataHelper;
import com.alpsoft.spotcheck.util.GlobalVar;
import com.alpsoft.spotcheck.util.SharedPreferencesUtils;
import com.alpsoft.spotcheck.util.TtsHelper;
import com.alpsoft.spotcheck.util.UpdateManager;
import com.alpsoft.spotcheck.util.Utils;
import com.alpsot.lkspotcheck.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

/**
 * 手持点检登录 znx 实现扫卡、离线、账号登录
 */

public class LoginActivity extends BaseActivity implements
        OnClickListener {
    /**
     * 初始化控件
     */
    @ViewInject(R.id.bt_cklogin)
    private Button btn_sklogin;
    @ViewInject(R.id.bt_lxlogin)
    private Button btn_lxlogin;
    @ViewInject(R.id.bt_login)
    private Button btn_zhlogin;
    private TextView usernameText;
    private TextView passwordText;

    /**
     * 所用到的属性
     */
    private DataHelper dh;
    private Context context;
    private Intent intent;
    public static boolean zhLogin = true;
    private Fragment fra;

    // 定义log字符串
    private static final String TAG = "LOGIN";
    int index = 1;
    private boolean supportScan;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        /**
         * 窗体加载时初始化操作
         */
        context = this;
        usernameText = (TextView) findViewById(R.id.act_login_et_username);
        passwordText = (TextView) findViewById(R.id.act_login_et_password);
        GlobalVar.ts = new TtsHelper(this);
        try {
            String model = Build.MODEL;
            supportScan = model.equalsIgnoreCase(HfDevice.DEV_AX6737) || model.equals(HfDevice.DEV_H901);
        } catch (SecurityException e) {
            e.printStackTrace();
            supportScan = false;
        }
        if (supportScan)
            initSysScan();
        ViewUtils.inject(this);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectNetwork()
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());
        UpdateManager updmge = new UpdateManager(this);
        updmge.checkUpdateInfo();
        dh = new DataHelper(this);

        // 绑定事件
        btn_lxlogin.setOnClickListener(this);
        btn_sklogin.setOnClickListener(this);
        btn_zhlogin.setOnClickListener(this);

        // 尝试解决home键退出后,再次点击icon 会进入主界面的问题.
        if (!isTaskRoot()) {
            finish();
            return;
        }
    }

    private void initSysScan() {
        try {
            String model = Build.MODEL;
            if (model.equalsIgnoreCase(HfDevice.DEV_AX6737)) {
                GlobalVar.ct = new Ax6737Reader(myHandler);
            } else {
                GlobalVar.ct = new H910Reader(myHandler);
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        GlobalVar.ct.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_cklogin:
                try {
                    if (GlobalVar.ct == null) {
                        Toast.makeText(this, "平台暂不支持！", Toast.LENGTH_LONG).show();
                        return;
                    }
                    if (index == 1) {
                        zhLogin = false;
                        showLoadingDialog("正在扫卡登录……");
                        GlobalVar.ct.scanUID();
                        index++;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.bt_lxlogin:
                if (dh.hasLocalData()) {
                    showLoadingDialog("正在离线登录，请稍后……");
                    User user = SharedPreferencesUtils.getLoginInfo(context);
                    if (user == null) {
                        hideLoadingDialog();
                        Toast.makeText(context, "无用户登录信息，请扫卡登录", Toast.LENGTH_SHORT);
                    } else {
                        intent = new Intent();
                        intent.setClass(context, SpotCheckMainActivity.class);
                        intent.putExtra("noLogin", "true");
                        context.startActivity(intent);
                        finish();
                    }
                } else {
                    Message message = new Message();
                    message.obj = "无数据,请扫工牌登录";
                    message.what = GlobalVar.msg_LoginFailure;
                    ((LoginActivity) context).myHandler.sendMessage(message);
                }
                break;
            case R.id.bt_login:
                String username = usernameText.getText().toString();
                String password = passwordText.getText().toString();
                if (TextUtils.isEmpty(username) || TextUtils.isEmpty(username)) {// 未输入账号密码,发出提示,不进行其他操作
                    Toast.makeText(context, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    showLoadingDialog("正在登录.请稍后...");
                    Utils.loginByName(context, fra, username, password, "login");
                }
                break;
        }
    }

    // 处理登录情况
    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GlobalVar.msg_LoginSuccess:
                    hideLoadingDialog();
                    GlobalVar.ts.speak("欢迎用户"
                            + SharedPreferencesUtils.getEmpName(context) + "登录系统");
                    msg.obj = "欢迎用户" + SharedPreferencesUtils.getEmpName(context)
                            + "登录系统";
                    intent = new Intent();
                    intent.setClass(context, SpotCheckMainActivity.class);
                    intent.putExtra("noLogin", "false");
                    context.startActivity(intent);
                    finish();
                    break;
                case GlobalVar.msg_LoginFailure:
                    hideLoadingDialog();
                    Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case GlobalVar.msg_UploadSuccess:
                    hideLoadingDialog();
                    GlobalVar.ts.speak("欢迎用户"
                            + SharedPreferencesUtils.getLoginInfo(context).getUserName() + "登录系统");
                    msg.obj = "欢迎用户" + SharedPreferencesUtils.getEmpName(context)
                            + "登录系统";
                    Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    intent = new Intent();
                    intent.setClass(context, SpotCheckMainActivity.class);
                    intent.putExtra("noLogin", "false");
                    context.startActivity(intent);
                    finish();
                    break;
                case CardThread.FIND:
                    String data = msg.getData().getString("data");
                    GlobalVar.ts.speak("嘀");
                    Utils.login(context, fra, data, "login");
                    break;
            }
        }
    };

    @Override
    public Handler getHandler() {
        Handler handler = this.myHandler;
        return handler;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GlobalVar.ct != null)
            GlobalVar.ct.setHandler(getHandler());
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (GlobalVar.ct != null) {
            GlobalVar.ct.stopPort();
            GlobalVar.ct = null;
        }
    }
}
